import 'package:flutter/material.dart';

class ColorGrid extends StatefulWidget {
  List<dynamic> list;
  int crossAxisCount = 2;
  Widget? Function(int, dynamic) withChild;
  bool Function(int) withHighLight;
  ColorGrid(
      {super.key, this.crossAxisCount = 2, required this.withHighLight, required this.list, required this.withChild});

  @override
  State<ColorGrid> createState() => _ColorGridState();
}

class _ColorGridState extends State<ColorGrid> {
  double gap = 5;

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (BuildContext context, BoxConstraints constriants) {
      var column = widget.list.length ~/ widget.crossAxisCount;
      return GridView.builder(
          physics: const NeverScrollableScrollPhysics(),
          padding: const EdgeInsets.only(top: 0, bottom: 0, left: 0, right: 0),
          itemCount: widget.list.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: widget.crossAxisCount,
              crossAxisSpacing: gap,
              mainAxisSpacing: gap,
              childAspectRatio: (constriants.maxWidth - gap * (widget.crossAxisCount - 1)) /
                  widget.crossAxisCount /
                  (constriants.maxHeight - gap * (column - 1)) *
                  column),
          itemBuilder: (BuildContext context, index) {
            return Container(
              padding: const EdgeInsets.all(0.4),
              decoration: BoxDecoration(
                  border: widget.withHighLight(index) ? null : Border.all(color: Colors.white, width: 0.4),
                  borderRadius: BorderRadius.circular(4)),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(4), // 给内部组件也设置圆角
                child: widget.withChild(index, widget.list[index]),
              ),
            );
          });
    });
  }
}
